package com.example.demo.service;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
// import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.example.demo.entity.Book;
import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    // 查看所有用户
    public Page<User> getUsers(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return userRepository.findAll(pageable);
    }

    // 新增的单一查询用户方法
    public User getUserById(String id) {
        return userRepository.findByName(id);
    }

    // 新增的单一查询用户方法
    public User updateUser(User user) {
        Optional<User> optionalUser = userRepository.findById(user.getId());
        if (optionalUser.isPresent()) {
            // 更新其他字段
            return userRepository.save(user);
        } else {
            throw new RuntimeException("User not found with id " + user.getId());
        }
    }

    // 新增的删除用户方法
    public void deleteUserById(Long id) {
        userRepository.deleteById(id);
    }

    public User loginUser(String username, String password) {
        User user = userRepository.findByName(username);
        if (user == null) {
            throw new RuntimeException("Invalid username or password");
        }
        return user;
    }

    public User registerUser(User user) {
        // 检查用户名是否已存在
        if (userRepository.findByName(user.getName()) != null) {
            throw new RuntimeException("Username already exists");
        }

        return userRepository.save(user);
    }

}